package com.ycxy.school.express.service.impl;

import com.ycxy.school.express.ex.ServiceException;
import com.ycxy.school.express.mapper.OrderEvaluateMapper;
import com.ycxy.school.express.mapper.OrderMapper;
import com.ycxy.school.express.pojo.dto.OrderEvaluateAddNewDTO;
import com.ycxy.school.express.pojo.entity.Order;
import com.ycxy.school.express.pojo.entity.OrderEvaluate;
import com.ycxy.school.express.pojo.vo.OrderEvaluateListItemVO;
import com.ycxy.school.express.security.LoginPrincipal;
import com.ycxy.school.express.service.IOrderEvaluateService;
import com.ycxy.school.express.service.IOrderService;
import com.ycxy.school.express.web.ServiceCode;
import com.ycxy.school.express.web.enums.OrderEvaluateEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author jayLuo
 * @Date 2023/1/12 13:39
 * @PackageName:com.ycxy.school.express.service.impl
 * @ClassName: OrderEvaluateServiceImpl
 * @Description: TODO
 * @Version 1.0
 */
@Slf4j
@Service
public class OrderEvaluateServiceImpl implements IOrderEvaluateService {

    @Autowired
    private OrderEvaluateMapper orderEvaluateMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Transactional
    @Override
    public void addNew(OrderEvaluateAddNewDTO orderEvaluateAddNewDTO, Long staffId, Long orderId) {
        log.debug("开始处理【新增订单评价数据】的业务,参数 :{}", orderEvaluateAddNewDTO);

        log.debug("即将检查订单号是否被占用……");
        {
            // 从参数对象中获取orderSn
            String orderSn = orderEvaluateAddNewDTO.getOrderSn();
            // 调用orderEvaluateMapper的countByOrderSn()方法执行统计查询
            int count = orderEvaluateMapper.countByOrderSn(orderSn);
            // 判断统计结果是否不等于0
            if (count != 0) {
                // 是：抛出异常
                String message = "添加订单评价失败，订单号【" + orderSn + "】已经被占用！";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
            }
        }
        //创建OrderEvaluate类
        OrderEvaluate orderEvaluate = new OrderEvaluate();
        LocalDateTime now = LocalDateTime.now();
        //同名属性赋值
        BeanUtils.copyProperties(orderEvaluateAddNewDTO, orderEvaluate);
        orderEvaluate.setUserId(getUserId());
        orderEvaluate.setStaffId(staffId);
        orderEvaluate.setUserDate(now);
        orderEvaluate.setCreateData(now);
        //调用OrderEvaluateMapper的insert方法
        int rows = orderEvaluateMapper.insert(orderEvaluate);
        // 判断插入数据的结果是否符合预期
        if (rows != 1) {
            String message = "添加评价数据失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }

        Order order = new Order();
        order.setId(orderId);
        order.setIsEvaluate(OrderEvaluateEnum.close.getType());
        int rows2 = orderMapper.updateById(order);
        if (rows2 != 1) {
            String message = "修改是否开启评价字段失败，服务器忙，请稍后再次尝试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【删除用户评价数据】的业务，参数：{}", id);
        // orderEvaluateMapper deleteById(Long id)执行删除，并获取返回的行数
        int rows = orderEvaluateMapper.deleteById(id);
        // 判断返回的行数是否不为1
        if (rows != 1) {
            // 是：抛出异常（ERR_DELETE：服务器忙）
            String message = "删除用户评价数据失败，服务器忙，请稍后再尝试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

    @Override
    public void addMessage(Long id,String addMessage) {
        log.debug("开始处理【用户追加评价】的业务，参数：{}", id);
        // orderEvaluateMapper updateById(Long id)执行删除，并获取返回的行数
        int rows = orderEvaluateMapper.updateById(id,addMessage);
        // 判断返回的行数是否不为1
        if (rows != 1) {
            // 是：抛出异常（ERR_DELETE：服务器忙）
            String message = "删除用户评价数据失败，服务器忙，请稍后再尝试！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

    @Override
    public List<OrderEvaluateListItemVO> listByUserId() {
        log.debug("开始处理【根据用户id查询订单评价数据】的业务");
        List<OrderEvaluateListItemVO> list = orderEvaluateMapper.listByUserId(getUserId());
        return list;
    }

    @Override
    public List<OrderEvaluateListItemVO> listByStaffId() {
        log.debug("开始处理【根据配送员id查询订单评价数据】的业务");
        List<OrderEvaluateListItemVO> list = orderEvaluateMapper.listByStaffId(getUserId());
        return list;
    }

    public LoginPrincipal getUserInfo() {
        // 编写获取SpringSecurity上下文的代码
        LoginPrincipal principal = (LoginPrincipal)
                SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // 为了逻辑严谨,判断一下SpringSecurity上下文中信息是不是null
        if (principal == null) {
            throw new ServiceException(
                    ServiceCode.ERR_UNAUTHORIZED, "您没有登录!");
        }
        return principal;
    }

    // 业务逻辑层需求中,实际上只需要用户的id
    // 我们可以再编写一个方法,从用户对象中获取id
    public Long getUserId() {
        return getUserInfo().getId();
    }

}
